package com.dbapp.shopping.controller;

import com.dbapp.shopping.service.Service;
import com.dbapp.shopping.domain.User;
import com.dbapp.shopping.security.RegistrationForm;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/register")
public class RegistrationController {

    private PasswordEncoder passwordEncoder;
    private Service service;

    public RegistrationController(PasswordEncoder passwordEncoder, Service service) {
        this.passwordEncoder = passwordEncoder;
        this.service = service;
    }

    @GetMapping
    public String registerForm(Model model)
    {
        model.addAttribute("result", true)
                .addAttribute("passwordempty", false)
                .addAttribute("usernameempty", false);
        return "registration";
    }

    @PostMapping
    public String processRegistration(Model model, RegistrationForm form) {
        boolean dupUsername, passowrd = false, username = false;
        User user = service.getUserByUsername(form.getUsername());
        model.addAttribute("result", true)
                .addAttribute("passwordempty", false)
                .addAttribute("usernameempty", false);

        if(form.getPassword().equals(""))
        {
            model.addAttribute("passwordempty", true);
            passowrd = true;
        }
        if(form.getUsername().equals(""))
        {
            model.addAttribute("usernameempty", true);
            username = true;
        }
        if(passowrd || username)
            return "registration";
        if (user != null) {
            model.addAttribute("result", false);
            return "registration";
        }
        else {
            User newuser = service.saveUser(form.toUser(passwordEncoder));
            return "redirect:/login";
        }
    }
}
